// components/nickname-avatar-popup/index.js
import Toast from "@vant/weapp/toast/toast"
const $api = require("../../request/api").API
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

    /**
     * 组件的初始数据
     */
    data: {
        show:false,
        nickName:"",
        avatarUrl:"",
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 显示组件弹框
        showPopup(val){
            this.setData({
                show:true,
                nickName:val.nickName,
                avatarUrl:val.avatarUrl,
            })
        },
        // 拒绝
        cancel(){
            this.setData({
                show:false,
            })
        },
        // 允许
        submit(){
            let reg = /\s/g
            let httpUrlReg =/^https/
            if(!this.data.avatarUrl){
                Toast.fail({
                    message:"请选择头像"
                })
                return
            }
            
            // 如果是专属商户不需要填写昵称
            if(!this.data.nickName.replace(reg,"")){
                Toast.fail({
                    message:"请输入昵称"
                })
                return
            }
            if(this.data.nickName.replace(reg,"")=="微信用户"){
                Toast.fail({
                    message:"昵称不能是微信用户"
                })
                return
            }

            let avatarBase = undefined
            let nickName = this.data.nickName.replace(reg,"")
            if(!httpUrlReg.test(this.data.avatarUrl)){
                // 只是本地临时路径转化为base64
                avatarBase = wx.getFileSystemManager().readFileSync(this.data.avatarUrl,"base64")
            }
            let params = {
                nickName:nickName,
                image:avatarBase
            }
            $api.setUserInfo(params).then(res=>{
                let avatarUrl = res.data.data
                this.triggerEvent("getInfo",{
                    nickName:nickName,
                    avatarUrl:avatarUrl,
                })
                wx.setStorageSync('nickName', nickName)
                wx.setStorageSync('avatarUrl', avatarUrl)
                this.setData({
                    show:false,
                })
                Toast.success("设置成功")
            })
        },
        // 获取头像
        getAvatar(e){
            wx.getFileSystemManager().getFileInfo({
                filePath:e.detail.avatarUrl,
                success:res=>{
                    if(res.size>3145728){
                        Toast.fail({
                            message:"图片过大,请重新选择"
                        })
                    }
                    this.setData({
                        avatarUrl:e.detail.avatarUrl
                    })
                }
            })
            

            
        },
    }
})
